# -*- coding: utf-8 -*-
import os
#import subprocess
import maya.cmds as cmds
import CommonModule
import ani
import shutil
import json
import getpass
import maya.mel as mel
#import xml.etree.cElementTree as ET
import datetime
#import ani.HUD as HUD
import re
from pipeline.pipeline_Path import *
import core as timelimit
import tempfile

if not cmds.pluginInfo ("fbxmaya.mll",q=1 ,l=1 ):
	cmds.evalDeferred('cmds.loadPlugin ("fbxmaya.mll")')
if not cmds.pluginInfo ("AbcExport.mll",q=1 ,l=1 ):
	cmds.evalDeferred('cmds.loadPlugin ("AbcExport.mll")')


class Plablast_min () :
	cmds.colorManagementPrefs(e=True, cmEnabled=1)
	#cmds.setAttr ("hardwareRenderingGlobals.enableTextureMaxRes" , 1)
	#cmds.setAttr ('hardwareRenderingGlobals.textureMaxResMode' , 1)
	#cmds.setAttr ('hardwareRenderingGlobals.textureMaxResolution' , 1280)
	#cmds.evalDeferred('mel.eval ("AEReloadAllTextures")')
	#mel.eval ('generateAllUvTilePreviews')

	# 路径拼写linux的文件转置写法
	
	Fonts = "C\\\:/Windows/Fonts/simhei.ttf"
	#print Fonts
	ffmpeg = "H:/RareWolf_Toolkit/Package/ffmpeg/ffmpeg.exe"
	# Min = int(cmds.playbackOptions (q =1,min=1))
	# Max = int(cmds.playbackOptions( q =1,max=1))
	cmds.setAttr("defaultResolution.w", int(LocalPath_ProjectSettingRead("ImageWidth")))
	cmds.setAttr("defaultResolution.h", int(LocalPath_ProjectSettingRead("ImageHeight")))
	print('*************************************')
	def __init__(self):

			#HUD.HUD_min().star_headsUpDisplay ()
		self.Project_Name =LocalPath_ProjectSettingRead("ProjectName")
		self.XlsxProject_Path = LocalPath_ProjectSettingRead("Project_XLSX")
		self.local_Path = LocalPath_ProjectSettingRead("Project_local_Path")
		self.ServerX_Project = LocalPath_ProjectSettingRead("Project_ServerX_Path")
		self.Server_MasterPath = self.ServerX_Project
		#self.Project_Sound = LocalPath_ProjectSettingRead("Project_ServerX_Path")

		'''
		user = getpass.getuser()
		ProjectSettings_LocalPath = 'C:/Users/' + user + '/Documents/RareWolf/'
		ProjectSettings_LocalFile = os.listdir(ProjectSettings_LocalPath)
		for tmp in ProjectSettings_LocalFile:
			if 'ProjectSettings' in tmp:
				with open(ProjectSettings_LocalPath + tmp, 'r') as f:
					json_data = json.load(f)
					self.Project_Name = json_data['Project_Name']
					self.XlsxProject_Path = json_data['Project_XLSX']
					# 本地路径
					self.local_Path = json_data['Project_local_Path']
					#网盘路径
					self.ServerX_Project = json_data['Project_ServerX_Path']
					print self.ServerX_Project
					self.Project_Sound = json_data['Project_ServerX_Path']
		'''
	def warning_Window(self):
		cmds.confirmDialog(message=u'注意！！！请在工程下制作文件,不要乱搞')
	def Plablast_bin(self):
		if timelimit.ProductActivation().Win() == 0:
			return
		if cmds.headsUpDisplay('HUDDate', ex=1):
			ani.HUD_min().star_headsUpDisplay ()

		ani.HUD_min().star_headsUpDisplay ()
		'''
		File_sceneName = cmds.file(q=1, sceneName=1)
		if not self.Project_Name in File_sceneName:
			print self.Project_Name
			print File_sceneName
			self.warning_Window()
			return
		'''

		File_sceneName = cmds.file(q=1, sceneName=1)
		File_shortName = cmds.file(q=1, sceneName=1, shortName=1)
		File_Path = os.path.dirname(File_sceneName)
		File_PathSplit = File_Path.split('/')

		Set = "("+LocalPath_ProjectSettingRead("Set")+ ")"
		Set_Split = "("+LocalPath_ProjectSettingRead("Set_Split")+ ")"
		Events = "("+LocalPath_ProjectSettingRead("Events")+ ")"
		Events_Split = "("+LocalPath_ProjectSettingRead("Events_Split")+ ")"
		Lens = "("+LocalPath_ProjectSettingRead("Lens")+ ")"
		Lens_Split = "("+LocalPath_ProjectSettingRead("Lens_Split")+ ")"

		ANIcals = "("+LocalPath_ProjectSettingRead("ANI")+ ")"
		LAYcals = "("+LocalPath_ProjectSettingRead("LAY")+ ")"
		Class_Split = "("+LocalPath_ProjectSettingRead("Class_Split")+ ")"
		Version = "("+LocalPath_ProjectSettingRead("Version")+ ")"
		VersionNumber = "("+LocalPath_ProjectSettingRead("VersionNumber")+ ")"
		FileFormat = "("+LocalPath_ProjectSettingRead("FileFormat")+ ")"
		ImageWidth = int(LocalPath_ProjectSettingRead("ImageWidth"))
		ImageHeight =  int(LocalPath_ProjectSettingRead("ImageHeight"))
		Project_Frame =int(LocalPath_ProjectSettingRead("Project_Frame") )

		#print ImageWidth,ImageHeight
		cals = ''
		if re.search(ANIcals, File_sceneName):
		#if ANIcals in File_shortName:
			self.ServerX_Project = self.ServerX_Project + '/' + File_PathSplit[-5]
			cals =ANIcals

		if re.search(LAYcals, File_sceneName):
		#if LAYcals in File_shortName:
			self.ServerX_Project = self.ServerX_Project + '/' + File_PathSplit[-5]
			cals = LAYcals
		ReFileName = str(Set + Set_Split + Events + Events_Split + Lens + Lens_Split + cals + Class_Split + Version + VersionNumber + FileFormat)

		print (ReFileName)
		print (File_sceneName)
		matchObj = re.search(ReFileName, File_sceneName)
		print (matchObj.group())
		#print(cals, File_PathSplit[-5])
		print ']]]]]]]]]]]]]]]]]]]]]]]]]'
		if matchObj:
			#print '000000000000000000'
			if re.search(cals, File_PathSplit[-5]):
				print(cals, File_PathSplit[-5])
				ReSet = re.search(matchObj.group(1), File_PathSplit[-4])
				print(matchObj.group(1), File_PathSplit[-4])
				#print '-----------------------------------'
				if ReSet:
					ReEvents = re.search(matchObj.group(3), File_PathSplit[-3])
					print(matchObj.group(3), File_PathSplit[-3])
					#print '+++++++++++++++++++++++++++++++++++++++'
					if ReEvents :
						ReLens = re.search(matchObj.group(5),  File_PathSplit[-2])

						print(matchObj.group(5),  File_PathSplit[-2])
						#print '////////////////////////////////////////////'
						if ReLens:
							#print File_PathSplit[-2]
							#print matchObj.group(5)
							pass
							#print  matchObj.group()
						else:
							print ('1')
							self.warning_Window()
							return u"文件名错误"
					else:
						print ('2')
						self.warning_Window()
						return u"文件名错误"
				else:
					print '3'
					self.warning_Window()
					return u"文件名错误"
			else:
				print '4'
				self.warning_Window()
				return u"文件名错误"

		else:
			print '5'
			self.warning_Window()
			return u"文件名错误"

		self.File_shortNameVersion = matchObj.group(1) + matchObj.group(2) + matchObj.group(3) + matchObj.group(4) + matchObj.group(5) + matchObj.group(6) + matchObj.group(7)
		print  self.File_shortNameVersion
		File_shortNameClass = matchObj.group(1) + matchObj.group(2) + matchObj.group(3) + matchObj.group(4) + matchObj.group(5) + matchObj.group(6) + matchObj.group(7) + matchObj.group(8) + matchObj.group(9) + matchObj.group(10)
		print(File_shortNameClass)
		#print '66666666666666666666666666666666666'

		cmds.file(save=1)
		MaxTime = int(cmds.playbackOptions(q=1, maxTime=1))
		MinTime = int(cmds.playbackOptions(q=1, minTime=1))


		ServerXPath = self.ServerX_Project + '/' + matchObj.group(1) + '/' + matchObj.group(3) + '/' + matchObj.group(5) + '/scenes/'
		ServerXPath_images = self.ServerX_Project + '/' + matchObj.group(1) + '/' + matchObj.group(3) + '/' + matchObj.group(5) + '/images/'
		ServerXPath_movies = self.ServerX_Project + '/' + matchObj.group(1) + '/' + matchObj.group(3) + '/' + matchObj.group(5) + '/movies/'
		ServerXPath_cache = self.ServerX_Project + '/' + matchObj.group(1) + '/' + matchObj.group(3) + '/' + matchObj.group(5) + '/cache/'
		ServerPath_info = self.ServerX_Project + '/' + matchObj.group(1) + '/' + matchObj.group(3) + '/' + matchObj.group(5) + '/info/'

		if not os.path.exists(ServerXPath):
			os.makedirs(ServerXPath)
		if not os.path.exists(ServerXPath_images):
			os.makedirs(ServerXPath_images)
		if not os.path.exists(ServerXPath_movies):
			os.makedirs(ServerXPath_movies)
		if not os.path.exists(ServerXPath_cache):
			os.makedirs(ServerXPath_cache)
		if not os.path.exists(ServerPath_info):
			os.makedirs(ServerPath_info)
		
		wsfullName = cmds.workspace(q=True, fullName=True)
		#print '555555555555555555555555555555'
		cmds.playblast(format="image", frame=101,completeFilename=wsfullName + '/images/' + self.File_shortNameVersion + '.jpg', fr=1, sequenceTime=0,clearCache=1, viewer=1, showOrnaments=1, fp=0, percent=100, compression="jpg", quality=100, widthHeight=[1280, 720])
		########################################
		commentStr = " -metadata comment="
		RfNodes = cmds.ls (rf = 1)
		refFile = cmds.file( q=1 ,r=1)
		referenceNodeTmp =[]
		for tmp in refFile:
			referenceNodeTmp.append(cmds.referenceQuery (tmp , referenceNode = 1))
		UnReferenceNode=list(set(RfNodes) ^ set(referenceNodeTmp))
		for UnReferenceNodeList in UnReferenceNode:
			cmds.lockNode ( UnReferenceNodeList , lock = 0 )
			cmds.delete ( UnReferenceNodeList )
		#print '88888888888888888888888888888888888'
		RfNodes = cmds.ls (rf = 1)
		'''
		#视频中写入信息暂时屏蔽
		for RfNode in RfNodes :
			if re.search ( "Light",RfNode) or re.search ( "UNKNOWN_REF_NODE",RfNode) or re.search ( "Face",RfNode):
				continue
			if cmds.referenceQuery (RfNode , il = 1) :
				RfMaPath = cmds.referenceQuery (RfNode , filename = 1)
				Rfnamespace = cmds.file (RfMaPath , q = 1 , ns = 1)
				commentStr += Rfnamespace + "\\n"
				commentStr += RfMaPath + "\\n"
		print commentStr
		'''
		CommonModule.PublicWindow()
		#材质显示
		mel.eval('generateAllUvTilePreviews')
		LocalImgPath = wsfullName + '/images/' + self.File_shortNameVersion + '.jpg'
		cmds.playblast(format="image", frame=101,completeFilename = LocalImgPath, fr=1, sequenceTime=0,clearCache=1, viewer=1, showOrnaments=1, fp=0, percent=100, compression="jpg", quality=100,widthHeight=[1280, 720])

		#print '*******************************'
		cmds.select (cl=1)
		temp_folder = tempfile.gettempdir()

		type = "png"
		scenepath = cmds.file(q=1,sn=1)
		MayaMov = wsfullName + '/movies/'
		
		scenepathsp = scenepath.split('/')
		scenename = scenepathsp[-1].split('.')[0]
		playblastTemp_folder =  os.path.join(temp_folder,scenename).replace("\\", "/")
		outputPath_Directory   = os.path.join(MayaMov,scenename + ".mov").replace("\\", "/")
		ani.Playblast().create_ass(outputPath_Directory,playblastTemp_folder,scenename,type,ImageWidth,ImageHeight)
		cmds.deleteUI('PublicWindow',window = True)

		wsfullName = cmds.workspace(q=True, fullName=True)
		ListCam_list = [i for i in cmds.listCameras (p = 1) if i != "persp"]
		ListCam = ListCam_list[0]
		Old_Cam = ''
		if cmds.nodeType (ListCam) == "camera" :
			Old_Cam = cmds.listRelatives (ListCam , p = True)[0]
		else :
			Old_Cam = ListCam
		if len (ListCam_list) == 1 :
			try:
				New_CamName = Old_Cam + "_OUT"
				New_Cam = cmds.rename (cmds.camera ()[0] , New_CamName)
				cmds.parentConstraint (Old_Cam , New_Cam , name = New_Cam + '_Constraint')
				New_Cam_shape = cmds.listRelatives (New_Cam , shapes = True , children = True)[0]
				Old_Cam_shape = cmds.listRelatives (Old_Cam , shapes = True , children = True)[0]
				cmds.connectAttr (Old_Cam_shape + ".focalLength" , New_Cam_shape + ".focalLength")
				cmds.connectAttr (Old_Cam_shape + ".filmFit" , New_Cam_shape + ".filmFit")
				cmds.connectAttr (Old_Cam_shape + ".horizontalFilmAperture" , New_Cam_shape + ".horizontalFilmAperture")
				cmds.connectAttr (Old_Cam_shape + ".verticalFilmAperture" , New_Cam_shape + ".verticalFilmAperture")
				cmds.connectAttr (Old_Cam_shape + ".lensSqueezeRatio" , New_Cam_shape + ".lensSqueezeRatio")
				cmds.connectAttr (Old_Cam_shape + ".fStop" , New_Cam_shape + ".fStop")
				cmds.connectAttr (Old_Cam_shape + ".focusDistance" , New_Cam_shape + ".focusDistance")
				cmds.connectAttr (Old_Cam_shape + ".shutterAngle" , New_Cam_shape + ".shutterAngle")
				cmds.connectAttr (Old_Cam_shape + ".centerOfInterest" , New_Cam_shape + ".centerOfInterest")

				st = cmds.playbackOptions (min = 1 , q = 1)
				et = cmds.playbackOptions (max = 1 , q = 1)
				cmds.select (New_Cam , replace = True)
				cmds.bakeResults (New_Cam , t = (st , et) , sb = 1)
				cmds.setAttr (New_Cam + ".tx" , lock = 1)
				cmds.setAttr (New_Cam + ".ty" , lock = 1)
				cmds.setAttr (New_Cam + ".tz" , lock = 1)
				cmds.setAttr (New_Cam + ".rx" , lock = 1)
				cmds.setAttr (New_Cam + ".ry" , lock = 1)
				cmds.setAttr (New_Cam + ".rz" , lock = 1)
				cmds.setAttr (New_Cam + ".sx" , lock = 1)
				cmds.setAttr (New_Cam + ".sy" , lock = 1)
				cmds.setAttr (New_Cam + ".sz" , lock = 1)
				cmds.setAttr (New_Cam + ".v" , lock = 1)
				cmds.setAttr (New_Cam_shape + ".hfa" , lock = 1)
				cmds.setAttr (New_Cam_shape + ".vfa" , lock = 1)
				cmds.setAttr (New_Cam_shape + ".fl" , lock = 1)
				cmds.setAttr (New_Cam_shape + ".lsr" , lock = 1)
				cmds.setAttr (New_Cam_shape + ".fs" , lock = 1)
				cmds.setAttr (New_Cam_shape + ".fd" , lock = 1)
				cmds.setAttr (New_Cam_shape + ".sa" , lock = 1)
				cmds.setAttr (New_Cam_shape + ".coi" , lock = 1)
				cmds.setAttr (New_Cam_shape + ".lls" , lock = 1)
				Export_Path = wsfullName + '/cache/' + matchObj.group(1) + matchObj.group(2) + matchObj.group(3) + matchObj.group(4) +matchObj.group(5) + matchObj.group(6)+matchObj.group(7)+"-cam.fbx"
				mel.eval ("FBXResetExport; "
						  "FBXExportInputConnections -v false; "
						  "FBXExportBakeComplexAnimation -v false; "
						  "FBXExportLights -v false; "
						  "FBXExportCameras -v true; "
						  "FBXExportInAscii -v true;"
						  "FBXExportFileVersion FBX201700;"
						  "FBXExportSmoothingGroups -v true; "
						  "FBXExportSmoothMesh -v true;"
						  "FBXExportApplyConstantKeyReducer -v false;"
						  "FBXExportBakeComplexAnimation -v true; "
						  "FBXExportBakeComplexStep -v true; "
						  "FBXExportCameras -v true;")
				mel.eval (('FBXExport -f \"{}\" -s').format (Export_Path))
				cmds.file(wsfullName + '/cache/' + matchObj.group(1) + matchObj.group(2) + matchObj.group(3) + matchObj.group(4) +matchObj.group(5) + matchObj.group(6)+matchObj.group(7)+"-cam" ,force=1, options="v=0;", typ="mayaAscii", pr=1, es=1)
				
				cmds.delete (cmds.ls (New_Cam))
				if cmds.window("FbxWarningWindow", exists=1):
					cmds.deleteUI('FbxWarningWindow', window=True)
			except :
				print (u"NO-未知错误-手动检查文件")
		#cmds.bakeResults(new_cam, t=(CommonModule.MinTimes(), CommonModule.MaxTimes()), sampleBy=1)
		#cmds.file(wsfullName + '/cache/' + matchObj.group(1) + matchObj.group(2) + matchObj.group(3) + matchObj.group(4) +matchObj.group(5) + matchObj.group(6)+matchObj.group(7)+"-cam" ,force=1, options="v=0;", typ="mayaAscii", pr=1, es=1)
		#cmds.file(wsfullName + '/cache/' + matchObj.group(1) + matchObj.group(2) + matchObj.group(3) + matchObj.group(4) +matchObj.group(5) + matchObj.group(6)+matchObj.group(7)+"-cam.fbx", force=1, options="v=0;", typ="FBX export", pr=1, es=1)
		
		#cmds.delete(new_cam)

		To_ServerScenePath = ServerXPath + self.File_shortNameVersion + matchObj.group(11)
		To_ServerMovPath = ServerXPath_movies + self.File_shortNameVersion + '.mov'
		To_ServerImgPath= ServerXPath_images + self.File_shortNameVersion + '.jpg'
		#print(To_ServerMovPath)
		#print(To_ServerImgPath)
		for tmp in os.listdir(wsfullName + '/scenes/') :
			log_info_txt = matchObj.group(1) + matchObj.group(2) + matchObj.group(3) + matchObj.group(4) +matchObj.group(5)  + matchObj.group(6) + matchObj.group(7) + '_log.txt'
			print(log_info_txt)
			if log_info_txt in tmp :
				log_info = wsfullName + '/scenes/' +tmp
				#log_info_ServerPath = ServerXPath + log_info_txt
				#print(log_info_ServerPath)
				shutil.copy(log_info, ServerPath_info)
		shutil.copy(File_sceneName, To_ServerScenePath)
		try:
			shutil.copy(outputPath_Directory, To_ServerMovPath)
		except:
			cmds.confirmDialog(message=u'拷贝失败，检查视频文件是否被占用')
		shutil.copy(LocalImgPath,To_ServerImgPath)
		print("---------------------------")
		shutil.copy(wsfullName + '/cache/' + matchObj.group(1) + matchObj.group(2) + matchObj.group(3) + matchObj.group(4) +matchObj.group(5) + matchObj.group(6)+matchObj.group(7)+ "-cam" +  matchObj.group(11),	ServerXPath_cache + matchObj.group(1) + matchObj.group(2) + matchObj.group(3) + matchObj.group(4) +matchObj.group(5) + matchObj.group(6)+matchObj.group(7)+ "-cam" +  matchObj.group(11))
		shutil.copy(wsfullName + '/cache/' + matchObj.group(1) + matchObj.group(2) + matchObj.group(3) + matchObj.group(4) +matchObj.group(5) + matchObj.group(6)+matchObj.group(7)+ "-cam.fbx",					ServerXPath_cache + matchObj.group(1) + matchObj.group(2) + matchObj.group(3) + matchObj.group(4) +matchObj.group(5) + matchObj.group(6)+matchObj.group(7)+ "-cam.fbx")

		NewReFileName = matchObj.group(1)  + matchObj.group(3)  +matchObj.group(5) + matchObj.group(6) + matchObj.group(7) + matchObj.group(11)
		if "_" in matchObj.group(1):
			setAllFilePath = self.Server_MasterPath + '/' + matchObj.group(1).split('_')[1]  + '/' + matchObj.group(7)
			print(setAllFilePath)
			if not os.path.exists(setAllFilePath):
				os.makedirs(setAllFilePath)
			try:
				shutil.copy(outputPath_Directory, setAllFilePath + '/' + matchObj.group(1)  + matchObj.group(3)  +matchObj.group(5) + matchObj.group(6) +matchObj.group(7)  + ".mov")
			except:
				cmds.confirmDialog(message=u'拷贝失败，检查视频文件是否被占用')
			shutil.copy(File_sceneName, setAllFilePath + '/' + NewReFileName)
		'''
		if not os.path.exists(self.ServerX_Project + '/' + Set.split('_')[0] + '/' +cals):
			os.makedirs(self.ServerX_Project + '/' + Set.split('_')[0] + '/' +cals)
		
		shutil.copy(MayaMov, self.ServerX_Project + '/' + Set.split('_')[0] + '/' +cals + '/' + NewReFileName + ".mov")
		shutil.copy(MayaMov, self.ServerX_Project + '/' + Set.split('_')[0] + '/' +cals + '/' + NewReFileName + FileFormat)
		'''
		# 获取信息
		assect_json = {}
		assect_json['NameVode'] = str(self.File_shortNameVersion)
		assect_json['Time'] = str(MinTime) + '-' + str(MaxTime)
		assect_json['TotalFrames'] = str(MaxTime - MinTime + 1)
		assect_json['date'] = str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
		assect_json['version'] = str(matchObj.group(10))
		#print '********************************************************************************'
		user = getpass.getuser()
	

		ProjectSettings_LocalPath = 'C:/Users/' + user + '/Documents/RareWolf/'
		ProjectSettings_LocalFile = os.listdir(ProjectSettings_LocalPath)
		for tmp in ProjectSettings_LocalFile:
			if 'UserName' in tmp:
				with open(ProjectSettings_LocalPath + tmp, 'r') as f:
					UserName_json_data = json.load(f)
					UserName = UserName_json_data['UserName']
					print(UserName)
				assect_json['UserName'] = UserName.encode('utf-8')
	
		# 导出信息

		json_Path = cmds.workspace ( fullName = True ) + '/info/' + self.File_shortNameVersion + '-publishInfo.json'
		#print  (json_Path)
		#out_file = open(json_Path, 'w')
		#json.dump(assect_json, out_file, indent=4)
		#out_file.close()
		with open(json_Path,'w') as file:
			json.dump(assect_json,file, ensure_ascii=False)

		shutil.copy(json_Path, ServerPath_info)
#Plablast_min ().Plablast_bin()